package com.hdsx.netty.rpcclient.netty;

import com.hdsx.netty.protocol.BasicProtocol;
import com.hdsx.netty.rpcclient.netty.handle.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;

/**
 * @author 占贤银
 * time 2024/8/14 21:13
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class NettyProxy implements InvocationHandler {

    private int port;

    public NettyProxy(int port) {
        this.port = port;
    }

    public <T> T createProxy(Class<T> aclazz) {
        return (T) Proxy.newProxyInstance(aclazz.getClassLoader(), new Class[]{aclazz}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        EventLoopGroup group = null;
        BasicProtocol basicProtocol = new BasicProtocol();
        basicProtocol.setClassName(method.getDeclaringClass().getName());
        basicProtocol.setMethodName(method.getName());
        basicProtocol.setParameterType(method.getParameterTypes());
        basicProtocol.setParameterValues(args);
        RpcClientHandler handler = new RpcClientHandler();
        try {
            group = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                            pipeline.addLast(new LengthFieldPrepender(4));
                            pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast(new ObjectEncoder());
                            pipeline.addLast(handler);
                        }
                    })
                    .option(ChannelOption.TCP_NODELAY, true);
            ChannelFuture future = bootstrap.connect(
                    new InetSocketAddress("127.0.0.1", this.port)).sync();
            future.channel().writeAndFlush(basicProtocol).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
        return handler.getResponse();
    }
}
